package de.revdev.llt.bean.facade;

import de.revdev.llt.bean.entities.Participants;
import de.revdev.llt.bean.entities.Participants_;
import de.revdev.llt.bean.entities.PublicClassRoom;
import de.revdev.llt.bean.entities.User;
import de.revdev.llt.bean.entities.User_;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;

/**
 *
 * @author f.lindermaier
 */
@Stateless
public class ParticipantsFacade extends AbstractFacade<Participants> {

    @PersistenceContext(unitName = "LetsLearnTogetherPU")
    private EntityManager em;

    @Override
    public EntityManager getEntityManager() {
        return em;
    }

    public ParticipantsFacade() {
        super(Participants.class);
    }

    public List<Participants> getInvitations(User user) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Participants> cq = cb.createQuery(Participants.class);
        Root<Participants> r = cq.from(Participants.class);
        cq.select(r);
        ParameterExpression<User> p = cb.parameter(User.class);
        ParameterExpression<Boolean> q = cb.parameter(Boolean.class);
        cq.where(cb.equal(r.get(Participants_.user), p), cb.equal(r.get(Participants_.accepted), q));
        return em.createQuery(cq).setParameter(p, user).setParameter(q, Boolean.FALSE).getResultList();
    }

    public Participants getParticipation(User user, PublicClassRoom publicClassRoom) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Participants> cq = cb.createQuery(Participants.class);
        Root<Participants> r = cq.from(Participants.class);
        cq.select(r);
        ParameterExpression<User> p = cb.parameter(User.class);
        ParameterExpression<PublicClassRoom> q = cb.parameter(PublicClassRoom.class);
        cq.where(cb.equal(r.get(Participants_.user), p), cb.equal(r.get(Participants_.publicClassRoom), q));
        return em.createQuery(cq).setParameter(p, user).setParameter(q, publicClassRoom).getSingleResult();
    }
}
